package com.bear.fastrepair.mvvm.ui.employee.fragment

import android.annotation.SuppressLint
import android.util.Log
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.bear.fastrepair.BuildConfig
import com.bear.fastrepair.MainActivity
import com.bear.fastrepair.R
import com.bear.fastrepair.base.BaseFragment
import com.bear.fastrepair.databinding.FragmentEmployeePersonalBinding
import com.bear.fastrepair.entity.EmployeeWorkStatus
import com.bear.fastrepair.entity.UpdateLocation
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModel
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModelFactory
import com.bear.fastrepair.mvvm.ui.employee.dialog.AppUpdateProgressDialog
import com.bear.fastrepair.mvvm.ui.employee.dialog.AppUpdateSelectDialog
import com.bear.fastrepair.utils.LocationHelper
import com.bear.fastrepair.utils.launch
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import java.io.File

class EmployeePersonalFragment : BaseFragment<FragmentEmployeePersonalBinding>() {

    private lateinit var globalViewModel: EmployeeViewModel
    private lateinit var privateViewModel: EmployeeViewModel

    override val title: String
        get() = getString(R.string.personal_center)

    @SuppressLint("SetTextI18n")
    override fun init() {
        val main = requireActivity() as MainActivity
        val navi = main.findViewById<BottomNavigationView>(R.id.bottom_navi_employee)
        navi?.visibility = View.VISIBLE
        globalViewModel = ViewModelProvider(
            requireActivity(),
            EmployeeViewModelFactory()
        ).get(EmployeeViewModel::class.java)
        privateViewModel = ViewModelProvider(
            this,
            EmployeeViewModelFactory()
        ).get(EmployeeViewModel::class.java)
        globalViewModel.getPersonalInfo()

        globalViewModel.personalInfo.observe(viewLifecycleOwner) {
            binding.workStatus.text =
                if (it.data.workStatus == 0) "休息中" else if (it.data.workStatus == 1) "工作中" else "未知状态"
            Glide.with(this).load(it.data.avatar).into(binding.avatar)
            binding.location.text = it.data.locationAddress
            binding.tvName.text = it.data.userName
        }


        binding.updateWorkStatus.setOnClickListener {
            AlertDialog.Builder(requireContext()).setTitle(R.string.update_work_status)
                .setSingleChoiceItems(
                    requireContext().resources.getStringArray(R.array.work_status),
                    globalViewModel.personalInfo.value?.data?.workStatus ?: 2
                ) { dialog, which ->
                    globalViewModel.updateWorkStatus(EmployeeWorkStatus(which))
                    dialog.dismiss()
                }.setCancelable(true).show()
        }

        binding.updateLocation.setOnClickListener {
            if (!XXPermissions.isGranted(
                    context,
                    Permission.ACCESS_FINE_LOCATION,
                    Permission.ACCESS_COARSE_LOCATION
                )
            ) {
                XXPermissions.with(context).permission(
                    Permission.ACCESS_FINE_LOCATION,
                    Permission.ACCESS_COARSE_LOCATION
                ).request(object : OnPermissionCallback {
                    override fun onGranted(
                        permissions: MutableList<String>?,
                        all: Boolean
                    ) {
                        globalViewModel.launch {
                            LocationHelper.getLocationInfo(requireContext()) {
                                if (it != null) {
                                    globalViewModel.updateLocation(
                                        UpdateLocation(
                                            it.address,
                                            it.latitude,
                                            it.longitude
                                        )
                                    )
                                }
                            }
                        }
                    }

                    override fun onDenied(
                        permissions: MutableList<String>?,
                        never: Boolean
                    ) {
                        super.onDenied(permissions, never)
                        ToastUtils.showLong("没有定位权限，请授予")
                        XXPermissions.startPermissionActivity(context)
                    }
                })
            } else {
                globalViewModel.launch {
                    LocationHelper.getLocationInfo(requireContext()) {
                        if (it != null) {
                            globalViewModel.updateLocation(
                                UpdateLocation(
                                    it.address,
                                    it.latitude,
                                    it.longitude
                                )
                            )
                        }
                    }
                }
            }
        }

        privateViewModel.updateApp.observe(viewLifecycleOwner) {
            if (it.code != 0) {
                ToastUtils.showLong("检查更新失败，请重试")
                return@observe
            }
            val localVersion = BuildConfig.VERSION_CODE
            val apkDir = File("${context?.externalCacheDir?.absolutePath}/apk")
            if (FileUtils.isFileExists(apkDir)) {
                apkDir.listFiles()?.let { files ->
                    if (files.isNotEmpty()) {
                        files.filter { file -> file.name.contains(".apk") }.forEach { apk ->
                            val apkInfo = AppUtils.getApkInfo(apk)
                            val versionCode = apkInfo?.versionCode ?: 0
                            val versionName = apkInfo?.versionName ?: ""
                            Log.i(
                                "bear_repair",
                                "init: apk versionCode: $versionCode, remote versionCode:${it.data.versionCode}, local versionCode:${localVersion}"
                            )
                            // 本地已下载安装包，对比与服务器中的版本，版本号较小不做安装
                            if (versionCode <= localVersion || versionCode < it.data.versionCode) {
                                Log.i("bear_repair", "init: apk version is more lower")
                                return@forEach
                            }
                            AppUpdateSelectDialog(requireContext(), versionName) { _ ->
                                AppUtils.installApp(apk)
                            }.show()
                            return@observe
                        }
                    }
                }
                FileUtils.deleteAllInDir(apkDir)
            }
            // 本地已安装
            if (localVersion >= it.data.versionCode) {
                ToastUtils.showShort("当前应用已是最新版本")
                Log.i("bear_repair", "init: local version is highest")
                return@observe
            }
            AppUpdateSelectDialog(
                requireContext(),
                versionName = it.data.versionName ?: "",
                description = it.data.description,
                createTime = it.data.createTime
            ) { _ ->
                AppUpdateProgressDialog(requireContext(), it.data, privateViewModel, this).show()
            }.show()
        }

        binding.updateApp.setOnClickListener {
            privateViewModel.updateApp()
        }

        binding.resetPassword.setOnClickListener {
            findNavController().popBackStack()
            findNavController().navigate(R.id.employeeResetPasswordFragment)
        }

        binding.appVersion.text = "版本：V${BuildConfig.VERSION_NAME}"

    }
}